﻿using LogionDemo.Common.Helper;
using LogionDemo.Common.Interfaces;
using LogionDemo.Common.UserEventArgs;
using LogionDemo.Models;

namespace LogionDemo.Controls.Base
{
	public abstract class AuditWithLoginBaseForm : AuditBaseForm<LoginStatusChangedEventArgs>, ILogin
	{
		private bool _isLoggedIn = false;

		public AuditWithLoginBaseForm()
		{
			CacheHelper.CacheItemExpiredEvent += CacheHelper_CacheItemExpiredEvent;
			UserToken = CacheHelper.Get<UserToken>();
			if (UserToken != null) { IsLoggedIn = true; }
			else { UpdateLoginMessage(); }
		}

		public event EventHandler<LoginStatusChangedEventArgs>? LoginStatusChangedEvent;

		public bool IsLoggedIn
		{
			get => _isLoggedIn;
			private set
			{
				if (Equals(_isLoggedIn, value)) { return; }
				var args = new LoginStatusChangedEventArgs(value, UserToken!);
				UpdateLoginMessage();
				_isLoggedIn = value;
				OnLoginStatusChanged(args);
			}
		}

		public string? LoginMessage { get; private set; }

		public UserToken? UserToken { get; private set; }

		public void CancelLogin()
		{
			DialogResult = DialogResult.Cancel;
		}

		public void Login()
		{
			LoginForm login = new LoginForm();
			if (login.ShowDialog() == DialogResult.OK)
			{
				UserToken = CacheHelper.Get<UserToken>();
				if (UserToken != null) { IsLoggedIn = true; }
				else { MessageBox.Show("登录失败，未找到Token"); }
			}
		}

		public void Logout()
		{
			CacheHelper.Remove();
			IsLoggedIn = false;
		}

		protected virtual void OnLoginStatusChanged(LoginStatusChangedEventArgs args)
		{
			if (IsLoggedIn) { LoginMessage = $"用户：{UserToken!.UserName},欢迎你！"; }
			else { LoginMessage = $"操作超时已经登出！"; }
			LoginStatusChangedEvent?.Invoke(this, args);
		}

		private void CacheHelper_CacheItemExpiredEvent(object? sender, CacheItemExpiredEventArgs e)
		{
			if (InvokeRequired) { Invoke(() => { IsLoggedIn = false; UserToken = null; }); }
			else { IsLoggedIn = false; UserToken = null; }
		}

		private void UpdateLoginMessage()
		{
			if (IsLoggedIn) { LoginMessage = $"用户：{UserToken!.UserName},欢迎你！"; }
			else { LoginMessage = $"操作超时已经登出！"; }
		}
	}
}